<template>
  <div>
    <el-select
      v-model="checkedId"
      v-loadMore="selectLoadMore"
      filterable
      remote
      placeholder="请选择证型,可输入证型名/首字母搜索,选择后在下方显示"
      clearable
      @change="handleChange"
      :remote-method="remoteMethod"
      :loading="loading"
      style="width: 100%"
    >
      <el-option
        v-for="item in options"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
        <div>({{ item.id }}) {{ item.name }}</div>
      </el-option>
    </el-select>
  </div>
</template>

<script>
import { getTCMList } from "@/api/saas/tcm.js";
import { arrayUnique } from '@/utils/ruoyi'

export default {
  data() {
    return {
      checkedId: undefined, // 选中的ID
      options: [],
      getParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined,
      },
      total: 0,
      loading: false,

    }
  },
  async created() {
    await this.getList();
  },
  methods: {
    async getList() {
      const { rows, total } = await getTCMList(this.getParams);
      this.total = total;
      if (this.getParams.pageNum === 1) { this.options = [] };
      this.options = arrayUnique([...this.options, ...rows], 'id');
    },
    // 下拉加载更多
    selectLoadMore() {
      if (this.options.length < this.total) {
        this.getParams.pageNum++;
        this.getList();
      }
    },
    async remoteMethod(query) {
      this.loading = true;
      this.getParams.pageNum = 1;
      this.getParams.pageSize = 10;
      this.getParams.keyword = query;
      await this.getList();
      this.loading = false;
    },
    handleChange(id) {
      if (!id) return
      const that = this;
      const currentItem = that.options.find(v => {
        return v.id === id;
      });
      that.$emit("change", currentItem);
      that.checkedId = undefined;
    },
  }
}
</script>

<style lang="scss" scoped>
</style>
